import {
  Ref,
  shallowRef,
  unref,
  onMounted,
  onDeactivated,
  onBeforeUnmount,
} from 'vue'

import echarts, { ECOption, MapParams } from '@/components/BaseEcharts/config'
import { GeoJSONSourceInput } from 'echarts/types/src/coord/geo/geoTypes.js'

export type EChartsCoreOption = ECOption

export const useEcharts = (
  elRef: Ref<HTMLDivElement>,
  options: EChartsCoreOption,
  map: MapParams
) => {
  const charts = shallowRef<echarts.ECharts>()

  const setOptions = (options: EChartsCoreOption) => {
    charts.value && charts.value.setOption(options)
  }

  const registerMap = async () => {
    let res = await fetch(map.geoJsonURL)
    let geoJSON: GeoJSONSourceInput = await res.json()

    echarts.registerMap(map.name, { geoJSON: geoJSON } as any)
  }

  // 初始化
  const initCharts = async (themeColor?: Array<string>) => {
    const el = unref(elRef)
    if (!el || !unref(el)) {
      return
    }
    charts.value = echarts.init(el)
    if (themeColor) {
      options.color = themeColor
    }
    if (map.name !== '') {
      await registerMap()
    }

    setOptions(options)
  }

  // 重新窗口变化时，重新计算
  const resize = () => {
    charts.value && charts.value.resize()
  }

  onMounted(() => {
    window.addEventListener('resize', resize)
  })

  // 页面keepAlive时，不监听页面
  onDeactivated(() => {
    window.removeEventListener('resize', resize)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resize)
  })

  return {
    initCharts,
    setOptions,
    resize,
  }
}
